package com.cqie.hospitalescort.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqie.hospitalescort.DTO.AuthUser;
import com.cqie.hospitalescort.DTO.EscortDTO;
import com.cqie.hospitalescort.DTO.IdDTO;
import com.cqie.hospitalescort.entity.AdminUser;
import com.cqie.hospitalescort.entity.EscortInfo;
import com.cqie.hospitalescort.entity.OnlineChatInfo;
import com.cqie.hospitalescort.entity.UserInfo;
import com.cqie.hospitalescort.enums.RoleEnum;
import com.cqie.hospitalescort.enums.StatusEnum;
import com.cqie.hospitalescort.exception.BusinessException;
import com.cqie.hospitalescort.mapper.AdminUserMapper;
import com.cqie.hospitalescort.mapper.EscortInfoMapper;
import com.cqie.hospitalescort.mapper.OnlineChatInfoMapper;
import com.cqie.hospitalescort.mapper.UserInfoMapper;
import com.cqie.hospitalescort.service.AdminUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.hospitalescort.service.file.AliYunService;
import com.cqie.hospitalescort.service.weixin.WeiXinService;
import com.cqie.hospitalescort.utils.Asserts;
import com.cqie.hospitalescort.utils.WebSecurityUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gdy
 * @since 2025-02-18
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private EscortInfoMapper escortInfoMapper;
    @Autowired
    private WeiXinService weChatService;
    @Autowired
    private OnlineChatInfoMapper messageMapper;

    /**
     * 成为陪诊员
     *
     * @param escortDTO
     */
    @Override
    @Transactional
    public void save(EscortDTO escortDTO) {
        if (Objects.nonNull(this.becomeList()))
            throw new BusinessException("单次只能提交一次申请！");
        AuthUser currentUser = WebSecurityUtil.getCurrentUser();
        EscortInfo escortInfo = Optional.ofNullable(escortInfoMapper.getEscortInfoById(currentUser.getId())).orElse(new EscortInfo());
        escortInfo.buildEscortInfo(escortDTO);
        escortInfo.setEscortStatus(StatusEnum.PRE.getCode());//待审核
        if(Objects.isNull(escortInfo.getId())){
            escortInfo.setId(currentUser.getId());//关联上用户id
        }

        //上传图片
        escortInfo.setPicture(String.join(",", escortDTO.getFiles()));

        //头像
        escortInfo.setAvatar(escortDTO.getAvatar());

        if(Objects.isNull(escortInfo.getId())){
            escortInfoMapper.insert(escortInfo);
        } else {
            escortInfo.setDeleteFlag(0);
            int i = escortInfoMapper.updateEscortInfo(escortInfo);
            if(i == 0)
                throw new BusinessException("更新失败！");
        }

    }

    /**
     * 审核成为陪诊员
     *
     * @param dto
     */
    @Override
    @Transactional
    public void auditUser(IdDTO dto) {
        Asserts.notEmpty(dto.getIds(), "id不能为空");
        List<UserInfo> userInfos = userInfoMapper.selectBatchIds(dto.getIds());
        userInfos.forEach(userInfo -> {
            //权限提升为陪诊员
            userInfo.setRole(RoleEnum.ESCORT.getRole());
            //审核陪诊员信息
            EscortInfo escortInfo = escortInfoMapper.selectById(userInfo.getId());
//            escortInfo.setId(userInfo.getId());
            escortInfo.setEscortStatus(StatusEnum.EMPTY.getCode());//修改状态为空闲
            escortInfoMapper.updateById(escortInfo);

            // 发送微信小程序通知
            weChatService.sendNotification(userInfo.getOpenid());

            OnlineChatInfo onlineChatInfo = new OnlineChatInfo();
            onlineChatInfo.setUserId(userInfo.getId());
            onlineChatInfo.setComment("您的陪诊员权限已开通，请重新登录以获取最新权限。");
            onlineChatInfo.setSenderType("后台开通");
            messageMapper.insert(onlineChatInfo);
        });

        userInfoMapper.updateById(userInfos, userInfos.size());
    }

    /**
     * 删除管理员
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAdminUser(IdDTO dto) {
        Asserts.notEmpty(dto.getIds(), "被删除人不能为空");
        List<AdminUser> adminUsers = adminUserMapper.selectBatchIds(dto.getIds());
        if (CollectionUtils.isEmpty(adminUsers)) {
            throw new BusinessException("人员不存在！");
        }

        adminUserMapper.deleteByIds(dto.getIds());
    }

    /**
     * 取消申请
     *
     * @param id
     */
    @Override
    @Transactional
    public void cancel(Long id) {
        EscortInfo escortInfo = escortInfoMapper.selectById(id);
        if (Objects.isNull(escortInfo)) throw new BusinessException("申请不存在");

        escortInfoMapper.deleteById(id);
    }

    /**
     * 申请列表
     *
     * @return
     */
    @Override
    public EscortInfo becomeList() {
        AuthUser currentUser = WebSecurityUtil.getCurrentUser();
        return escortInfoMapper.selectOne(
                new LambdaQueryWrapper<EscortInfo>()
                .eq(EscortInfo::getId, currentUser.getId())
                .eq(EscortInfo::getEscortStatus, StatusEnum.PRE.getCode())
        );
    }
}
